﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SqlCeManager.Tools;
using System.Data.SqlServerCe;
using ProgNetComponentsDx.Options;
using DevExpress.XtraEditors.Repository;

namespace SqlCeManager
{
    public partial class TableDataForm : XtraForm
    {
        private DataTable SourceTable = new DataTable();

        private string _TableName;
        private ConnectionNode _Node;
        
        public TableDataForm()
        {
            InitializeComponent();
        }
        public TableDataForm(string table, ConnectionNode node) : this()
        {
            _Node = node;
            _TableName = table;
            DataRow[] rows = node.SchemaDataSet.COLUMNS.Select("CHARACTER_MAXIMUM_LENGTH >= " + OptionCache.GetOptionValue(Init.InitFormOptionNames.Main.DlugoscTekstuDlaMemo).AsInt());
            GetData();
            foreach (DataRow r in rows)
            {
                if (SourceTable.Columns.Contains(r["COLUMN_NAME"].AsString()) && SourceTable.Columns[r["COLUMN_NAME"].AsString()].DataType == typeof(string))
                {
                    reps.Add(r["COLUMN_NAME"].AsString(), repMemo);
                }
            }
            languageProvider1.GetSettings(this).Surfix = " [" + table + "]";
        }
        Dictionary<string, RepositoryItem> reps = new Dictionary<string, RepositoryItem>();
        private void GetData()
        {
            try
            {
                memoEdit1.Text = "";
                this.gcMain.DataSource = null;
                SourceTable.Clear();
                SourceTable.AcceptChanges();
                SourceTable.Columns.Clear();
                _Node.Adapter.SelectCommand.CommandText = "SELECT * FROM " + _TableName;
                _Node.Adapter.Fill(SourceTable);
                SourceTable.AcceptChanges();
                this.gcMain.DataSource = SourceTable;
                gvMain.Columns.Clear();
                gvMain.PopulateColumns();
                gcMain.RefreshDataSource();
                gvMain.BestFitWithName();

            }
            catch (Exception ex)
            {
                memoEdit1.Text = ex.Message;
                if (splitContainerControl1.Collapsed)
                    splitContainerControl1.Collapsed = false;
            }
        }

        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GetData();
        }

        private void bbiRollback_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SourceTable.RejectChanges();
            gcMain.RefreshDataSource();
        }

        private void bbiCommit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SqlCeCommandBuilder builder = null;
            try
            {
                memoEdit1.Text = "";
                _Node.Adapter.SelectCommand.CommandText = "SELECT * FROM " + _TableName;
                builder = new SqlCeCommandBuilder(_Node.Adapter);

                _Node.Adapter.UpdateCommand = builder.GetUpdateCommand();
                _Node.Adapter.InsertCommand = builder.GetInsertCommand();
                _Node.Adapter.DeleteCommand = builder.GetDeleteCommand();
                int i = _Node.Adapter.Update(SourceTable);
                memoEdit1.Text = languageProvider1.GetString("ROWS_UPDATED", i);
                SourceTable.AcceptChanges();
                gcMain.RefreshDataSource();
            }
            catch (Exception ex)
            {
                memoEdit1.Text = ex.Message;
                if (splitContainerControl1.Collapsed)
                    splitContainerControl1.Collapsed = false;
            }
            finally
            {
                if (builder != null)
                    builder.Dispose();
            }
        }

        private void gvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                gvMain.DeleteSelectedRows();
        }

        private void gvMain_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            if (reps.ContainsKey(e.Column.FieldName))
            {
                e.RepositoryItem = reps[e.Column.FieldName];
            }
        }
    }
}
